package com.example.a13001.shoppingmalltemplate.activitys;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.a13001.shoppingmalltemplate.R;
import com.example.a13001.shoppingmalltemplate.adapters.GridImageAdapter;
import com.example.a13001.shoppingmalltemplate.base.AppConstants;
import com.example.a13001.shoppingmalltemplate.base.BaseActivity;
import com.example.a13001.shoppingmalltemplate.manager.DataManager;
import com.example.a13001.shoppingmalltemplate.modle.CommonResult;
import com.example.a13001.shoppingmalltemplate.modle.UpFile;
import com.example.a13001.shoppingmalltemplate.utils.FullyGridLayoutManager;
import com.example.a13001.shoppingmalltemplate.utils.GlideUtils;
import com.example.a13001.shoppingmalltemplate.utils.MyUtils;
import com.example.a13001.shoppingmalltemplate.utils.Utils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.luck.picture.lib.tools.PictureFileUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import am.widget.drawableratingbar.DrawableRatingBar;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

public class GoEvaluateActivity extends BaseActivity {

    @BindView(R.id.iv_title_back)
    ImageView ivTitleBack;
    @BindView(R.id.tv_title_center)
    TextView tvTitleCenter;
    @BindView(R.id.recycler_goevaluate)
    RecyclerView recyclerGoevaluate;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.rl_root)
    RelativeLayout rlRoot;
    @BindView(R.id.drb_goevaluate_level)
    DrawableRatingBar drbGoevaluateLevel;
    @BindView(R.id.et_goevaluate_lable)
    EditText etGoevaluateLable;
    @BindView(R.id.et_goevaluate_xinde)
    EditText etGoevaluateXinde;
    @BindView(R.id.tv_goevaluate_commit)
    TextView tvGoevaluateCommit;
    @BindView(R.id.iv_goevaluate_logo)
    ImageView ivGoevaluateLogo;
    @BindView(R.id.tv_goevaluate_price)
    TextView tvGoevaluatePrice;
    @BindView(R.id.iv_goevaluate_number)
    TextView ivGoevaluateNumber;
    @BindView(R.id.tv_goevaluate_goodsname)
    TextView tvGoevaluateGoodsname;
    @BindView(R.id.iv_goevaluate_guige)
    TextView ivGoevaluateGuige;
    private GridImageAdapter adapter;
    private List<LocalMedia> selectList = new ArrayList<>();
    private static final String TAG = "GoEvaluateActivity";
    private DataManager manager;
    private CompositeSubscription mCompositeSubscription;
    private CommonResult mCommonResult;
    private String code;
    private String timeStamp;
    private int mCartId;
    private int mCommodityId;
    private List<String> mListImage = new ArrayList<>();
    StringBuffer buf;
    private String mCartimg;
    private int mNumber;
    private Double mPrice;
    private UpFile mUpFile;
    private List<String> mListImg = new ArrayList<>();
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {

            }
        }
    };
    private String mProperty;
    private String mGoodsName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_go_evaluate);
        ButterKnife.bind(this);
        initData();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }

    /**
     * 初始化数据源
     */
    private void initData() {
        mCompositeSubscription = new CompositeSubscription();
        manager = new DataManager(GoEvaluateActivity.this);

        String safetyCode = MyUtils.getMetaValue(GoEvaluateActivity.this, "safetyCode");
        code = Utils.md5(safetyCode + Utils.getTimeStamp());
        timeStamp = Utils.getTimeStamp();

        tvTitleCenter.setText("商品评价");

        if (getIntent() != null) {
            mCartId = getIntent().getIntExtra("cartid", 0);
            mCommodityId = getIntent().getIntExtra("commodityId", 0);
            mNumber = getIntent().getIntExtra("number", 0);
            mPrice = getIntent().getDoubleExtra("price", 0);
            mCartimg = getIntent().getStringExtra("cartimg");
            mProperty = getIntent().getStringExtra("property");
            mGoodsName = getIntent().getStringExtra("name");
        }
        GlideUtils.setNetImage(GoEvaluateActivity.this, AppConstants.INTERNET_HEAD + mCartimg, ivGoevaluateLogo);
        tvGoevaluatePrice.setText("价格：¥" + mPrice);
        ivGoevaluateNumber.setText("数量X" + mNumber);
        tvGoevaluateGoodsname.setText(mGoodsName);
        ivGoevaluateGuige.setText(mProperty);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(GoEvaluateActivity.this, 4, GridLayoutManager.VERTICAL, false);
        recyclerGoevaluate.setLayoutManager(manager);
        adapter = new GridImageAdapter(GoEvaluateActivity.this, onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(9);
        recyclerGoevaluate.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (selectList.size() > 0) {
                    LocalMedia media = selectList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 1:
                            // 预览图片 可自定长按保存路径
                            //PictureSelector.create(GoEvaluateActivity.this).themeStyle(themeId).externalPicturePreview(position, "/custom_file", selectList);
                            PictureSelector.create(GoEvaluateActivity.this).themeStyle(R.style.picture_default_style).openExternalPreview(position, selectList);
                            break;
                        case 2:
                            // 预览视频
                            PictureSelector.create(GoEvaluateActivity.this).externalPictureVideo(media.getPath());
                            break;

                    }
                }
            }
        });

        // 清空图片缓存，包括裁剪、压缩后的图片 注意:必须要在上传完成后调用 必须要获取权限
        RxPermissions permissions = new RxPermissions(this);
        permissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Boolean aBoolean) {
                if (aBoolean) {
                    PictureFileUtils.deleteCacheDirFile(GoEvaluateActivity.this);
                } else {
                    Toast.makeText(GoEvaluateActivity.this,
                            getString(R.string.picture_jurisdiction), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });
    }

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {

            // 进入相册 以下是例子：不需要的api可以不写
            PictureSelector.create(GoEvaluateActivity.this)
                    .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture_white_style,R.style.picture_QQ_style,R.style.picture_Sina_style
                    .maxSelectNum(9)// 最大图片选择数量
                    .minSelectNum(1)// 最小选择数量
                    .imageSpanCount(4)// 每行显示个数
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                    .previewImage(true)// 是否可预览图片
                    .previewVideo(true)// 是否可预览视频
                    .enablePreviewAudio(true) // 是否可播放音频
                    .isCamera(true)// 是否显示拍照按钮
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    //.imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                    //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
                    .enableCrop(false)// 是否裁剪
                    .compress(true)// 是否压缩
                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
//                        .compressSavePath(getPath())//压缩图片保存地址
//                        .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                    .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                        .withAspectRatio(aspect_ratio_x, aspect_ratio_y)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                    .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                    .isGif(false)// 是否显示gif图片
                    .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                    .circleDimmedLayer(false)// 是否圆形裁剪
                    .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                    .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                    .openClickSound(false)// 是否开启点击声音
                    .selectionMedia(selectList)// 是否传入已选图片
                    //.isDragFrame(false)// 是否可拖动裁剪框(固定)
//                        .videoMaxSecond(15)
//                        .videoMinSecond(10)
                    //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                    //.cropCompressQuality(90)// 裁剪压缩质量 默认100
                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                    //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                    //.rotateEnabled(true) // 裁剪是否可旋转图片
                    //.scaleEnabled(true)// 裁剪是否可放大缩小图片
                    //.videoQuality()// 视频录制质量 0 or 1
                    //.videoSecond()//显示多少秒以内的视频or音频也可适用
                    //.recordVideoSecond()//录制视频秒数 默认60s
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code

        }

    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:

                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
//                    listImage = new ArrayList<>();

                    for (LocalMedia media : selectList) {
//                        Log.e(TAG, "onActivityResult: 图片-----》" + media.getPath());
//                        String ss = MyUtils.imageToBase64(media.getPath());
//                        String ss=media.getPath();
//                        listImage.add(ss);
//                        buf.append(ss).append(",");

//                        Log.e(TAG, "onActivityResult: 图片-----》" + buf.toString());
                    }
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    @OnClick({R.id.iv_title_back, R.id.tv_goevaluate_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_title_back:
                onBackPressed();
                break;
            case R.id.tv_goevaluate_commit:
                String content = etGoevaluateXinde.getText().toString().trim();
                String lable = etGoevaluateLable.getText().toString().trim();
                int level = drbGoevaluateLevel.getRating();
                if (TextUtils.isEmpty(content)) {
                    Toast.makeText(this, "评论内容不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(lable)) {
                    Toast.makeText(this, "标签不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (selectList == null || selectList.size() <= 0) {
                    Toast.makeText(this, "请上传图片", Toast.LENGTH_SHORT).show();
                    return;
                }

                buf = new StringBuffer();
                for (LocalMedia media : selectList) {
                    File file = new File(media.getPath());
                    RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), file);
                    MultipartBody.Part part = MultipartBody.Part.createFormData("filePath", file.getName(), requestBody);
                    upFile(AppConstants.COMPANY_ID, code, timeStamp, part, content, lable, level);
                }

                break;
        }
    }

    /**
     * 自定义压缩存储地址
     *
     * @return
     */
    private String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/Luban/image/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }

    /**
     * ★ 提交商品评价信息
     *
     * @param companyid
     * @param code
     * @param timestamp
     * @param cartid         商品购物车ID
     * @param commodityid    商品ID
     * @param commentcontent 商品评价内容
     * @param commentlevel   商品评价星级
     * @param commentlabel   商品评价标签，多个用“|”线分割
     * @param commentimages  商品评价晒图
     * @return
     */
    public void commitEvaluate(String companyid, String code, String timestamp, int cartid, int commodityid, String commentcontent, int commentlevel, String commentlabel, String commentimages) {

        mCompositeSubscription.add(manager.commitEvaluate(companyid, code, timestamp, cartid, commodityid, commentcontent, commentlevel, commentlabel, commentimages)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new rx.Observer<CommonResult>() {
                    @Override
                    public void onCompleted() {
                        Log.e(TAG, "onCompleted: " + mCommonResult.toString());
                        int status = mCommonResult.getStatus();
                        if (status > 0) {
                            Toast.makeText(GoEvaluateActivity.this, "评价成功", Toast.LENGTH_SHORT).show();
                            finish();
                        } else {

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError: " + "请求失败" + e.toString());

                    }

                    @Override
                    public void onNext(CommonResult commonResult) {
                        mCommonResult = commonResult;
                    }
                }));
    }

    /**
     * 上传文件
     */
    public void upFile(String companyid, final String code, String timestamp, MultipartBody.Part file, final String content, final String lable, final int level) {

        mCompositeSubscription.add(manager.upFile(companyid, code, timestamp, file)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new rx.Observer<UpFile>() {
                    @Override
                    public void onCompleted() {
                        Log.e(TAG, "onCompleted: " + mUpFile.toString());
                        int status = mUpFile.getStatus();
                        if (status > 0) {
                            mListImage.add(mUpFile.getData());
                            Log.e(TAG, "onCompleted: " + mListImage.toString());
                            if (mListImage.size() == selectList.size()) {
                                Log.e(TAG, "onViewClicked: " + mListImage.toString());
                                for (int i = 0; i < mListImage.size(); i++) {
                                    buf.append(mListImage.get(i)).append("|");
                                }
                                if (buf.length() > 0) {
                                    //方法一  : substring
                                    System.out.println(buf.substring(0, buf.length() - 1));
//                            //方法二 ：replace
//                            System.out.println(buf.replace(buf.length() - 1, buf.length(), ""));
//                            //方法三： deleteCharAt
//                            System.out.println(buf.deleteCharAt(buf.length()-1));
                                }
                                Log.e(TAG, "onActivityResult: 图片--buf---》" + buf.toString());
//                Log.e(TAG, "onViewClicked: code==" + code + "==timeStamp==" + timeStamp + "==mCartId=="
//                        + mCartId + "==mCommodityId==" + mCommodityId + "==content==" + content + "==level=="
//                        + level + "==lable==" + lable + "==listImage.toString()==" + buf.toString());
                                commitEvaluate(AppConstants.COMPANY_ID, code, timeStamp, mCartId, mCommodityId, content, level, lable, buf.toString());
                            }
                        } else {

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError: " + "请求失败" + e.toString());

                    }

                    @Override
                    public void onNext(UpFile upFile) {
                        mUpFile = upFile;
                    }
                }));

    }

    ;
}
